package com.huatek.springframework.view.extn;

import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.HierarchicalMessageSource;
import org.springframework.validation.FieldError;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.view.AbstractView;

import flexjson.JSONSerializer;

/**
 *
 * @author dhrubo
 *
 *
 */

public class AjaxView extends AbstractView {
	public static final int VALIDATE_ERROR_CODE = 3000;
	public static final String ajaxErrorMessage = "ajaxErrorMessage";
	public static final String ajaxSuccessMessage = "ajaxSuccessMessage";
	public static final String formLable = "formLable";
	private static final Log log = LogFactory.getLog(AjaxView.class);
	HierarchicalMessageSource messageSource;

	public void setMessageSource(HierarchicalMessageSource messageSource) {
		this.messageSource = messageSource;
	}

	public void setLocaleResolver(LocaleResolver localeResolver) {
		this.localeResolver = localeResolver;
	}

	LocaleResolver localeResolver;

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.springframework.web.servlet.view.AbstractView#renderMergedOutputModel
	 * (java.util.Map, javax.servlet.http.HttpServletRequest,
	 * javax.servlet.http.HttpServletResponse)
	 */

	@SuppressWarnings("unchecked")
	@Override
	protected void renderMergedOutputModel(Map map, HttpServletRequest request,

	HttpServletResponse response) throws Exception {
		response.setContentType("text/plain; charset=UTF-8");
		log.info("Resolving ajax request view -" + map);
		String jsonString = null;
		JSONSerializer serializer = new JSONSerializer();
		if (map.containsKey(ajaxErrorMessage)) {
			response.setStatus(VALIDATE_ERROR_CODE);
			List<FieldError> errors = (List<FieldError>) map
					.get(ajaxErrorMessage);
			// Map<String, String> errorMap = new HashMap<String, String>();
			StringBuffer buffer = new StringBuffer();
			Object formName = map.get(formLable);
			if (messageSource == null || localeResolver == null) {
				for (int i = 0; i < errors.size(); i++) {
					if (buffer.length() > 0) {
						buffer.append(",");
					}
					buffer.append("\"" + errors.get(i).getField()).append(
							"\":\"").append(errors.get(i).getDefaultMessage())
							.append("\"");
				}
			} else {
				Locale locale = localeResolver.resolveLocale(request);
				for (int i = 0; i < errors.size(); i++) {
					String errorInfo = null;

					try {
						errorInfo = messageSource.getMessage(errors.get(i)
								.getCode(), errors.get(i).getArguments(),
								locale);
					} catch (Exception e) {
						log.warn("Can not find the message resource " + locale
								+ " for " + errors.get(i).getCode());
						errorInfo = errors.get(i).getDefaultMessage();
					}
					if (formName != null) {
						String messageInfo = null;
						String fieldMessage = formName + "."
								+ errors.get(i).getField() + ".displayName";
						try {
							messageInfo = messageSource.getMessage(
									fieldMessage, null, locale);
						} catch (Exception e) {
							log.warn("Can not find the message resource "
									+ locale + " for  " + fieldMessage);
							messageInfo = errors.get(i).getField();
						}
						errorInfo = messageInfo + errorInfo;
					}
					if (buffer.length() > 0) {
						buffer.append(",");
					}
					buffer.append("\"" + errors.get(i).getField()).append(
							"\":\"").append(errorInfo).append("\"");
				}
			}
			jsonString = "{" + buffer.toString() + "}";

		} else if (map.containsKey(ajaxSuccessMessage)) {
			jsonString = serializer.serialize(new HashMap<String, String>());
		} else {
			jsonString = serializer.serialize(map);
		}

		response.getOutputStream().write(jsonString.getBytes("utf-8"));

	}

}
